/*
 * Copyright (C) 2017 Jared Rummler
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.jaredrummler.ohos.colorpicker;

import com.jaredrummler.ohos.colorpicker.utils.ColorUtils;
import com.jaredrummler.ohos.colorpicker.utils.Log;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.*;
import ohos.agp.components.AttrHelper;
import ohos.agp.utils.Color;
import ohos.agp.window.dialog.CommonDialog;
import ohos.agp.window.service.WindowManager;
import ohos.app.Context;
import ohos.global.resource.NotExistException;
import ohos.global.resource.WrongTypeException;
import ohos.multimodalinput.event.TouchEvent;
import ohos.utils.PacMap;

import java.io.IOException;
import java.util.*;

/**
 * <p>A dialog to pick a color.</p>
 *
 * <p>The {@link ohos.aafwk.ability.Ability activity} that shows this dialog should implement {@link ColorPickerDialogListener}</p>
 *
 * <p>Example usage:</p>
 *
 * <pre>
 *   ColorPickerDialog.newBuilder().show(activity);
 * </pre>
 */
public class ColorPickerDialog extends CommonDialog implements ColorPickerView.OnColorChangedListener, Text.TextObserver, Component.ClickedListener {

    private static String validCharacter = "abcdefABCDEF0987654321";

    static String filterValidCharacter(String str){
        StringBuffer sb = new StringBuffer();
        for(int i = 0; i< str.length(); i++){
            Character c = str.charAt(i);
            if(validCharacter.indexOf(c) == -1)
                continue;
            sb.append(c);
        }
        return sb.toString();
    }

    private static final String TAG = "ColorPickerDialog";

    public static final int TYPE_CUSTOM = 0;
    public static final int TYPE_PRESETS = 1;

    private Context mContext;

    /**
     * Material design colors used as the default color presets
     */
    public static final int[] MATERIAL_COLORS = {
            0xFFF44336, // RED 500
            0xFFE91E63, // PINK 500
            0xFFFF2C93, // LIGHT PINK 500
            0xFF9C27B0, // PURPLE 500
            0xFF673AB7, // DEEP PURPLE 500
            0xFF3F51B5, // INDIGO 500
            0xFF2196F3, // BLUE 500
            0xFF03A9F4, // LIGHT BLUE 500
            0xFF00BCD4, // CYAN 500
            0xFF009688, // TEAL 500
            0xFF4CAF50, // GREEN 500
            0xFF8BC34A, // LIGHT GREEN 500
            0xFFCDDC39, // LIME 500
            0xFFFFEB3B, // YELLOW 500
            0xFFFFC107, // AMBER 500
            0xFFFF9800, // ORANGE 500
            0xFF795548, // BROWN 500
            0xFF607D8B, // BLUE GREY 500
            0xFF9E9E9E, // GREY 500
    };

    static final int ALPHA_THRESHOLD = 165;

    private static final String ARG_ID = "id";
    private static final String ARG_TYPE = "dialogType";
    private static final String ARG_COLOR = "color";
    private static final String ARG_ALPHA = "alpha";
    private static final String ARG_PRESETS = "presets";
    private static final String ARG_ALLOW_PRESETS = "allowPresets";
    private static final String ARG_ALLOW_CUSTOM = "allowCustom";
    private static final String ARG_DIALOG_TITLE = "dialogTitle";
    private static final String ARG_SHOW_COLOR_SHADES = "showColorShades";
    private static final String ARG_COLOR_SHAPE = "colorShape";
    private static final String ARG_PRESETS_BUTTON_TEXT = "presetsButtonText";
    private static final String ARG_CUSTOM_BUTTON_TEXT = "customButtonText";
    private static final String ARG_SELECTED_BUTTON_TEXT = "selectedButtonText";

    ColorPickerDialogListener colorPickerDialogListener;
    StackLayout rootView;
    int[] presets;
    int color;
    int dialogType;
    int dialogId;
    boolean showColorShades;
    int colorShape;

    // -- PRESETS --------------------------
    ColorPaletteAdapter adapter;
    DirectionalLayout shadesLayout;
    Slider transparencySeekBar;
    Text transparencyPercText;

    // -- CUSTOM ---------------------------
    ColorPickerView colorPicker;
    ColorPanelView newColorPanel;
    TextField hexEditText;
    boolean showAlphaSlider;
    private boolean fromEditText;

    // --pacMap------------------------------
    private PacMap mPacMap;

    // self define

    public ColorPickerDialog(Context context, PacMap args) {
        super(context);
        setArguments(args);
        mContext = context;
        onStart();
    }

    public void dismiss() {
        // onDismiss
        onDialogDismissed();
    }

    private final Component.TouchEventListener onPickerTouchListener = new Component.TouchEventListener() {
        @Override
        public boolean onTouchEvent(Component v, TouchEvent touchEvent) {
            if (v != hexEditText && hexEditText.hasFocus()) {
                return true;
            }
            return false;
        }
    };

    /**
     * Create a new Builder for creating a {@link ColorPickerDialog} instance
     *
     * @return The {@link Builder builder} to create the {@link ColorPickerDialog}.
     */
    public static Builder newBuilder() {
        return new Builder();
    }

    public void setArguments(PacMap pacMap) {
        mPacMap = pacMap;
    }

    public PacMap getArguments() {
        if (mPacMap == null) {
            mPacMap = new PacMap();
        }
        return mPacMap;
    }

    private void onCreateDialog(PacMap savedInstanceState) {
        this.setAutoClosable(true);
        dialogId = getArguments().getIntValue(ARG_ID);
        showAlphaSlider = getArguments().getBooleanValue(ARG_ALPHA);
        showColorShades = getArguments().getBooleanValue(ARG_SHOW_COLOR_SHADES);
        colorShape = getArguments().getIntValue(ARG_COLOR_SHAPE);
        if (savedInstanceState == null) {
            color = getArguments().getIntValue(ARG_COLOR);
            dialogType = getArguments().getIntValue(ARG_TYPE);
        } else {
            color = savedInstanceState.getIntValue(ARG_COLOR);
            dialogType = savedInstanceState.getIntValue(ARG_TYPE);
        }

        rootView = new StackLayout(getFractionAbility());
        rootView.setWidth(ComponentContainer.LayoutConfig.MATCH_PARENT);
        Component contentView = null;
        if (dialogType == TYPE_CUSTOM) {
            rootView.addComponent(contentView = createPickerView());
        } else if (dialogType == TYPE_PRESETS) {
            contentView = createPresetsView();
            contentView.setWidth(ComponentContainer.LayoutConfig.MATCH_PARENT);
            rootView.addComponent(contentView);
        }

        int selectedButtonStringRes = getArguments().getIntValue(ARG_SELECTED_BUTTON_TEXT);
        if (selectedButtonStringRes == 0) {
            selectedButtonStringRes = ResourceTable.String_cpv_select;
        }

        this.setContentCustomComponent(rootView);
        try {
            setPositiveButton(mContext.getResourceManager().getElement(selectedButtonStringRes).getString(), (view)->{
                onColorSelected(color);
            });
        } catch (IOException | NotExistException | WrongTypeException e) {
            e.printStackTrace();
        }

        int dialogTitleStringRes = getArguments().getIntValue(ARG_DIALOG_TITLE);
        if (dialogTitleStringRes != 0) {
            try {
                String dialogTitleStringResStr = getFractionAbility().getResourceManager().getElement(dialogTitleStringRes).getString();
                DirectionalLayout layout = new DirectionalLayout(mContext);
                Text text = new Text(mContext);
                text.setText(dialogTitleStringResStr);
                text.setTextSize(20, Text.TextSizeType.FP);
                text.setMarginsLeftAndRight(80, 50);
                text.setMarginsTopAndBottom(80, 0);

                layout.addComponent(text);
                this.setTitleCustomComponent(layout);
            } catch (IOException | NotExistException | WrongTypeException e) {
                e.printStackTrace();
            }
        }

        int presetsButtonStringRes = getArguments().getIntValue(ARG_PRESETS_BUTTON_TEXT);
        int customButtonStringRes = getArguments().getIntValue(ARG_CUSTOM_BUTTON_TEXT);

        int neutralButtonStringRes;
        if (dialogType == TYPE_CUSTOM && getArguments().getBooleanValue(ARG_ALLOW_PRESETS)) {
            neutralButtonStringRes = (presetsButtonStringRes != 0 ? presetsButtonStringRes : ResourceTable.String_cpv_presets);
        } else if (dialogType == TYPE_PRESETS && getArguments().getBooleanValue(ARG_ALLOW_CUSTOM)) {
            neutralButtonStringRes = (customButtonStringRes != 0 ? customButtonStringRes : ResourceTable.String_cpv_custom);
        } else {
            neutralButtonStringRes = 0;
        }

        if (neutralButtonStringRes != 0 && contentView != null) {
            try {
                String neutralButtonString = getFractionAbility().getResourceManager().getElement(neutralButtonStringRes).getString();
                this.setNeutralButton(contentView, neutralButtonString, this);
            } catch (IOException | NotExistException | WrongTypeException e) {
                e.printStackTrace();
            }
        }

    }

    public CommonDialog setPositiveButton(String text, Component.ClickedListener listener) {
        Button button = (Button) rootView.findComponentById(ResourceTable.Id_positiveButton);
        button.setClickedListener(listener);
        button.setText(text);
        return this;
    }

    public void setNeutralButton(Component content, String text, Component.ClickedListener listener) {
        Button button = (Button) content.findComponentById(ResourceTable.Id_neutralButton);
        button.setClickedListener(listener);
        button.setText(text);
    }

    public void onStart() {
        onCreateDialog(null);

        this.getWindow()
                .clearFlags(WindowManager.LayoutConfig.MARK_FOCUSABLE_IMPOSSIBLE | WindowManager.LayoutConfig.MARK_ALT_FOCUSABLE_IM);
    }

    /**
     * Set the callback.
     * <p/>
     * Note: The preferred way to handle the callback is to have the calling Ability implement
     * {@link ColorPickerDialogListener} as this will not survive an orientation change.
     *
     * @param colorPickerDialogListener The callback invoked when a color is selected or the dialog is dismissed.
     */
    public void setColorPickerDialogListener(ColorPickerDialogListener colorPickerDialogListener) {
        this.colorPickerDialogListener = colorPickerDialogListener;
    }

    // region Custom Picker

    Component createPickerView() {
        Component contentView = LayoutScatter.getInstance(getFractionAbility()).parse(ResourceTable.Layout_cpv_dialog_color_picker, null, false);
        colorPicker = (ColorPickerView) contentView.findComponentById(ResourceTable.Id_cpv_color_picker_view);
        ColorPanelView oldColorPanel = (ColorPanelView) contentView.findComponentById(ResourceTable.Id_cpv_color_panel_old);
        newColorPanel = (ColorPanelView) contentView.findComponentById(ResourceTable.Id_cpv_color_panel_new);
        Text arrowRight = (Text) contentView.findComponentById(ResourceTable.Id_cpv_arrow_right);
        hexEditText = (TextField) contentView.findComponentById(ResourceTable.Id_cpv_hex);

        try {
            int arrowColor = Color.BLACK.getValue();
            arrowRight.setTextColor(new Color(arrowColor));
        } catch (Exception ignored) {
        }

        colorPicker.setAlphaSliderVisible(showAlphaSlider);
        oldColorPanel.setColor(getArguments().getIntValue(ARG_COLOR));
        colorPicker.setColor(color, true);
        newColorPanel.setColor(color);
        setHex(color);

        newColorPanel.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component v) {
                if (newColorPanel.getColor() == color) {
                    onColorSelected(color);
                    dismiss();
                }
            }
        });

        contentView.setTouchEventListener(onPickerTouchListener);
        colorPicker.setOnColorChangedListener(this);
        hexEditText.addTextObserver(this);

        hexEditText.setFocusChangedListener(new Component.FocusChangedListener() {
            @Override
            public void onFocusChange(Component component, boolean hasFocus) {
            }
        });

        return contentView;
    }

    @Override
    public void onColorChanged(int newColor) {
        color = newColor;
        if (newColorPanel != null) {
            newColorPanel.setColor(newColor);
        }
        if (!fromEditText && hexEditText != null) {
            setHex(newColor);
            if (hexEditText.hasFocus()) {
                hexEditText.clearFocus();
            }
        }
        fromEditText = false;
    }

    @Override
    public void onTextUpdated(String s, int start, int before, int count) {
        Log.e("onTextUpdated", "s:" + s + " start:"  + start + " before:" + before + " count:" + count);
        String finalStr = s;
        if(s.length() > before) {
            // count means count number char added
            int maxLength = showAlphaSlider ? 8 : 6;
            // there is a bug of onTextUpdated, start is chaos, and the only thing I can do for now, is filter all the string, and trim the whole string

            //            // new added string part
            //            String newString = s.substring(start, start + count);
            //            // filter with invalid character
            //            String filteredString  = filterValidCharacter(newString);
            //            // old part
            //            String oldLeft = s.substring(0, start);
            //            String oldRight = s.substring(start + count);
            //
            //            // bigger than the maxLength
            //            if (before + filteredString.length() > maxLength) {
            //                hexEditText.setText(oldLeft + filteredString.substring(0, maxLength - before) + oldRight);
            //                return;// 不继续处理， 等待下一次触发
            //            } else if(filteredString.length() != newString.length()){
            //                hexEditText.setText(oldLeft + filteredString + oldRight);
            //                return;
            //            }
            String filteredString  = filterValidCharacter(s);
            if(filteredString.length() > maxLength){
                filteredString = filteredString.substring(0, maxLength);
                hexEditText.setText(filteredString);
                finalStr = filteredString;
            } else if(filteredString.length() != s.length()) {
                // something filter and changed
                hexEditText.setText(filteredString);
                finalStr = filteredString;
            }

        }

        if (hexEditText.isFocused()) {
            int color = parseColorString(finalStr);
            if (color != colorPicker.getColor()) {
                fromEditText = true;
                colorPicker.setColor(color, true);
            }
        }
    }

    private void setHex(int color) {
        if (showAlphaSlider) {
            hexEditText.setText(String.format("%08X", (color)));
        } else {
            hexEditText.setText(String.format("%06X", (0xFFFFFF & color)));
        }
    }

    private int parseColorString(String colorString) throws NumberFormatException {
        int a, r, g, b = 0;
        if (colorString.startsWith("#")) {
            colorString = colorString.substring(1);
        }
        if (colorString.length() == 0) {
            r = 0;
            a = 255;
            g = 0;
        } else if (colorString.length() <= 2) {
            a = 255;
            r = 0;
            b = Integer.parseInt(colorString, 16);
            g = 0;
        } else if (colorString.length() == 3) {
            a = 255;
            r = Integer.parseInt(colorString.substring(0, 1), 16);
            g = Integer.parseInt(colorString.substring(1, 2), 16);
            b = Integer.parseInt(colorString.substring(2, 3), 16);
        } else if (colorString.length() == 4) {
            a = 255;
            r = Integer.parseInt(colorString.substring(0, 2), 16);
            g = r;
            r = 0;
            b = Integer.parseInt(colorString.substring(2, 4), 16);
        } else if (colorString.length() == 5) {
            a = 255;
            r = Integer.parseInt(colorString.substring(0, 1), 16);
            g = Integer.parseInt(colorString.substring(1, 3), 16);
            b = Integer.parseInt(colorString.substring(3, 5), 16);
        } else if (colorString.length() == 6) {
            a = 255;
            r = Integer.parseInt(colorString.substring(0, 2), 16);
            g = Integer.parseInt(colorString.substring(2, 4), 16);
            b = Integer.parseInt(colorString.substring(4, 6), 16);
        } else if (colorString.length() == 7) {
            a = Integer.parseInt(colorString.substring(0, 1), 16);
            r = Integer.parseInt(colorString.substring(1, 3), 16);
            g = Integer.parseInt(colorString.substring(3, 5), 16);
            b = Integer.parseInt(colorString.substring(5, 7), 16);
        } else if (colorString.length() == 8) {
            a = Integer.parseInt(colorString.substring(0, 2), 16);
            r = Integer.parseInt(colorString.substring(2, 4), 16);
            g = Integer.parseInt(colorString.substring(4, 6), 16);
            b = Integer.parseInt(colorString.substring(6, 8), 16);
        } else {
            b = -1;
            g = -1;
            r = -1;
            a = -1;
        }
        return Color.argb(a, r, g, b);
    }

    // -- endregion --

    // region Presets Picker

    Component createPresetsView() {
        Component contentView = LayoutScatter.getInstance(getFractionAbility()).parse(ResourceTable.Layout_cpv_dialog_presets, null, false);
        shadesLayout = (DirectionalLayout) contentView.findComponentById(ResourceTable.Id_shades_layout);
        transparencySeekBar = (Slider) contentView.findComponentById(ResourceTable.Id_transparency_seekbar);
        transparencyPercText = (Text) contentView.findComponentById(ResourceTable.Id_transparency_text);
        NestedGridView gridView = (NestedGridView) contentView.findComponentById(ResourceTable.Id_gridView);
        TableLayoutManager manager = new TableLayoutManager();
        manager.setColumnCount(4);
        gridView.setLayoutManager(manager);

        loadPresets();

        if (showColorShades) {
            createColorShades(color);
        } else {
            shadesLayout.setVisibility(Component.INVISIBLE);
            contentView.findComponentById(ResourceTable.Id_shades_divider).setVisibility(Component.INVISIBLE);
        }

        adapter = new ColorPaletteAdapter(new ColorPaletteAdapter.OnColorSelectedListener() {
            @Override
            public void onColorSelected(int newColor) {
                if (color == newColor) {
                    // Double tab selects the color
                    ColorPickerDialog.this.onColorSelected(color);
                    dismiss();
                    return;
                }
                color = newColor;
                if (showColorShades) {
                    createColorShades(color);
                }
            }
        }, presets, getSelectedItemPosition(), colorShape);

        gridView.setItemProvider(adapter);

        if (showAlphaSlider) {
            setupTransparency();
        } else {
            contentView.findComponentById(ResourceTable.Id_transparency_layout).setVisibility(Component.INVISIBLE);
            contentView.findComponentById(ResourceTable.Id_transparency_title).setVisibility(Component.INVISIBLE);
        }

        return contentView;
    }

    private void loadPresets() {
        int alpha = Color.alpha(color);
        presets = getArguments().getIntValueArray(ARG_PRESETS);
        if (presets == null) presets = MATERIAL_COLORS;
        boolean isMaterialColors = presets == MATERIAL_COLORS;
        presets = Arrays.copyOf(presets, presets.length); // don't update the original array when modifying alpha
        if (alpha != 255) {
            // add alpha to the presets
            for (int i = 0; i < presets.length; i++) {
                RgbColor color = RgbColor.fromArgbInt(presets[i]);
                int red = color.getRed();
                int green = color.getGreen();
                int blue = color.getBlue();
                presets[i] = Color.argb(alpha, red, green, blue);
            }
        }
        presets = unshiftIfNotExists(presets, color);
        int initialColor = getArguments().getIntValue(ARG_COLOR);
        if (initialColor != color) {
            // The user clicked a color and a configuration change occurred. Make sure the initial color is in the presets
            presets = unshiftIfNotExists(presets, initialColor);
        }
        if (isMaterialColors && presets.length == 19) {
            // Add black to have a total of 20 colors if the current color is in the material color palette
            presets = pushIfNotExists(presets, Color.argb(alpha, 0, 0, 0));
        }
    }

    void createColorShades(final int color) {
        final int[] colorShades = getColorShades(color);

        if (shadesLayout.getChildCount() != 0) {
            for (int i = 0; i < shadesLayout.getChildCount(); i++) {
                StackLayout layout = (StackLayout) shadesLayout.getComponentAt(i);
                final ColorPanelView cpv = (ColorPanelView) layout.findComponentById(ResourceTable.Id_cpv_color_panel_view);
                Text iv = (Text) layout.findComponentById(ResourceTable.Id_cpv_color_image_view);
                cpv.setColor(colorShades[i]);
                cpv.setTag(false);
                iv.setTextColor(Color.TRANSPARENT);
            }
            return;
        }

        String horizontalPaddingStr = "8vp";
        try {
            horizontalPaddingStr = getFractionAbility().getResourceManager().getElement(ResourceTable.String_cpv_item_horizontal_padding).getString();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NotExistException e) {
            e.printStackTrace();
        } catch (WrongTypeException e) {
            e.printStackTrace();
        }
        final int horizontalPadding = AttrHelper.convertDimensionToPix(getFractionAbility(), horizontalPaddingStr, 0);

        for (final int colorShade : colorShades) {
            int layoutResId;
            if (colorShape == ColorShape.SQUARE) {
                layoutResId = ResourceTable.Layout_cpv_color_item_square;
            } else {
                layoutResId = ResourceTable.Layout_cpv_color_item_circle;
            }
            final Component view = LayoutScatter.getInstance(getFractionAbility()).parse(layoutResId, null, false);
            // final Component view = Component.inflate(getFractionAbility(), layoutResId, null);
            final ColorPanelView colorPanelView = (ColorPanelView) view.findComponentById(ResourceTable.Id_cpv_color_panel_view);

            ComponentContainer.LayoutConfig params = (ComponentContainer.LayoutConfig) colorPanelView.getLayoutConfig();
            params.setMarginLeft(horizontalPadding);
            params.setMarginRight(horizontalPadding);
            colorPanelView.setLayoutConfig(params);
            colorPanelView.setColor(colorShade);
            shadesLayout.addComponent(view);

            getFractionAbility().getMainTaskDispatcher().asyncDispatch(new Runnable() {
                @Override
                public void run() {
                    // The color is black when rotating the dialog. This is a dirty fix. WTF!?
                    colorPanelView.setColor(colorShade);
                }
            });
            colorPanelView.setClickedListener(new Component.ClickedListener() {
                @Override
                public void onClick(Component v) {
                    if (v.getTag() instanceof Boolean && (Boolean) v.getTag()) {
                        onColorSelected(ColorPickerDialog.this.color);
                        dismiss();
                        return; // already selected
                    }
                    ColorPickerDialog.this.color = colorPanelView.getColor();
                    adapter.selectNone();
                    for (int i = 0; i < shadesLayout.getChildCount(); i++) {
                        StackLayout layout = (StackLayout) shadesLayout.getComponentAt(i);
                        ColorPanelView cpv = (ColorPanelView) layout.findComponentById(ResourceTable.Id_cpv_color_panel_view);
                        Text iv = (Text) layout.findComponentById(ResourceTable.Id_cpv_color_image_view);
                        iv.setText(cpv == v ? "√" : "");
                        if (cpv == v)
                            if (ColorUtils.calculateLuminance(cpv.getColor()) >= 0.65
                                    || Color.alpha(cpv.getColor()) <= ALPHA_THRESHOLD) {
                                Log.i("viewLayout", "setBlack");
                                iv.setTextColor(Color.BLACK);
                            } else {
                                Log.i("viewLayout", "setWHITE");
                                iv.setTextColor(Color.WHITE);
                            }
                        cpv.setTag(cpv == v);
                    }
                }
            });
            colorPanelView.setLongClickedListener(new Component.LongClickedListener() {
                @Override
                public void onLongClicked(Component component) {
                    colorPanelView.showHint();
                }
            });
        }
    }

    private void onColorSelected(int color) {
        if (colorPickerDialogListener != null) {
            Log.w(TAG, "Using deprecated listener which may be remove in future releases");
            colorPickerDialogListener.onColorSelected(dialogId, color);
            this.remove();
            return;
        }
        Context context = getFractionAbility();
        if (context instanceof ColorPickerDialogListener) {
            ((ColorPickerDialogListener) context).onColorSelected(dialogId, color);
            this.remove();
        } else {
            throw new IllegalStateException("The activity must implement ColorPickerDialogListener");
        }
    }

    private void onDialogDismissed() {
        if (colorPickerDialogListener != null) {
            Log.w(TAG, "Using deprecated listener which may be remove in future releases");
            colorPickerDialogListener.onDialogDismissed(dialogId);
            this.remove();
            return;
        }
        Context context = getFractionAbility();
        if (context instanceof ColorPickerDialogListener) {
            ((ColorPickerDialogListener) context).onDialogDismissed(dialogId);
            this.remove();
        }
    }

    private int shadeColor(int color, double percent) {
        String hex = String.format("#%06X", (0xFFFFFF & color));
        long f = Long.parseLong(hex.substring(1), 16);
        double t = percent < 0 ? 0 : 255;
        double p = percent < 0 ? percent * -1 : percent;
        long R = f >> 16;
        long G = f >> 8 & 0x00FF;
        long B = f & 0x0000FF;
        int alpha = Color.alpha(color);
        int red = (int) (Math.round((t - R) * p) + R);
        int green = (int) (Math.round((t - G) * p) + G);
        int blue = (int) (Math.round((t - B) * p) + B);
        return Color.argb(alpha, red, green, blue);
    }

    private int[] getColorShades(int color) {
        return new int[]{
                shadeColor(color, 0.9), shadeColor(color, 0.7), shadeColor(color, 0.5), shadeColor(color, 0.333),
                shadeColor(color, 0.166), shadeColor(color, -0.125), shadeColor(color, -0.25), shadeColor(color, -0.375),
                shadeColor(color, -0.5), shadeColor(color, -0.675), shadeColor(color, -0.7), shadeColor(color, -0.775),
        };
    }

    private void setupTransparency() {
        int progress = 255 - Color.alpha(color);
        transparencySeekBar.setMaxValue(255);
        transparencySeekBar.setProgressValue(progress);
        int percentage = (int) ((double) progress * 100 / 255);
        transparencyPercText.setText(String.format(Locale.ENGLISH, "%d%%", percentage));
        transparencySeekBar.setValueChangedListener(new Slider.ValueChangedListener() {
            @Override
            public void onProgressUpdated(Slider slider, int progress, boolean fromUser) {
                int percentage = (int) ((double) progress * 100 / 255);
                transparencyPercText.setText(String.format(Locale.ENGLISH, "%d%%", percentage));
                int alpha = 255 - progress;
                // update items in GridView:
                for (int i = 0; i < adapter.colors.length; i++) {
                    RgbColor color = RgbColor.fromArgbInt(adapter.colors[i]);
                    int red = color.getRed();
                    int green = color.getGreen();
                    int blue = color.getBlue();
                    adapter.colors[i] = Color.argb(alpha, red, green, blue);
                }
                adapter.notifyDataChanged();
                // update shades:
                for (int i = 0; i < shadesLayout.getChildCount(); i++) {
                    StackLayout layout = (StackLayout) shadesLayout.getComponentAt(i);
                    ColorPanelView cpv = (ColorPanelView) layout.findComponentById(ResourceTable.Id_cpv_color_panel_view);
                    Text iv = (Text) layout.findComponentById(ResourceTable.Id_cpv_color_image_view);
                    if (layout.getTag() == null) {
                        // save the original border color
                        layout.setTag(cpv.getBorderColor());
                    }
                    RgbColor rgbColor = RgbColor.fromArgbInt(cpv.getColor());
                    int color = Color.argb(alpha, rgbColor.getRed(), rgbColor.getGreen(), rgbColor.getBlue());
                    if (alpha <= ALPHA_THRESHOLD) {
                        cpv.setBorderColor(color | 0xFF000000);
                    } else {
                        cpv.setBorderColor((int) layout.getTag());
                    }
                    if (cpv.getTag() != null && (Boolean) cpv.getTag()) {
                        // The alpha changed on the selected shaded color. Update the checkmark color filter.
                        if (alpha <= ALPHA_THRESHOLD) {
                            iv.setTextColor(Color.BLACK);
                        } else {
                            if (ColorUtils.calculateLuminance(color) >= 0.65) {
                                iv.setTextColor(Color.BLACK);
                            } else {
                                iv.setTextColor(Color.WHITE);
                            }
                        }
                    }
                    cpv.setColor(color);
                }
                // update color:
                RgbColor rgbColor = RgbColor.fromArgbInt(color);
                int red = rgbColor.getRed();
                int green = rgbColor.getGreen();
                int blue = rgbColor.getBlue();
                color = Color.argb(alpha, red, green, blue);
            }

            @Override
            public void onTouchStart(Slider slider) {

            }

            @Override
            public void onTouchEnd(Slider slider) {

            }
        });
    }

    private int[] unshiftIfNotExists(int[] array, int value) {
        boolean present = false;
        for (int i : array) {
            if (i == value) {
                present = true;
                break;
            }
        }
        if (!present) {
            int[] newArray = new int[array.length + 1];
            newArray[0] = value;
            System.arraycopy(array, 0, newArray, 1, newArray.length - 1);
            return newArray;
        }
        return array;
    }

    private int[] pushIfNotExists(int[] array, int value) {
        boolean present = false;
        for (int i : array) {
            if (i == value) {
                present = true;
                break;
            }
        }
        if (!present) {
            int[] newArray = new int[array.length + 1];
            newArray[newArray.length - 1] = value;
            System.arraycopy(array, 0, newArray, 0, newArray.length - 1);
            return newArray;
        }
        return array;
    }

    private int getSelectedItemPosition() {
        for (int i = 0; i < presets.length; i++) {
            if (presets[i] == color) {
                return i;
            }
        }
        return -1;
    }

    private Context getFractionAbility() {
        return mContext;
    }

    @Override
    public void onClick(Component component) {
        this.destroy();

        switch (dialogType) {
            case TYPE_CUSTOM:
                mPacMap.putIntValue(ARG_TYPE, TYPE_PRESETS);
                break;
            case TYPE_PRESETS:
                mPacMap.putIntValue(ARG_TYPE, TYPE_CUSTOM);
                break;
        }
        mPacMap.putIntValue(ARG_COLOR, color);
        ColorPickerDialog dialog = newBuilder().create(mContext, mPacMap);
        dialog.setColorPickerDialogListener(colorPickerDialogListener);
        dialog.show();
    }
    // endregion

    // region Builder

    /*@IntDef({ TYPE_CUSTOM, TYPE_PRESETS })*/ public @interface DialogType {

    }

    public static final class Builder {

        ColorPickerDialogListener colorPickerDialogListener;
        /* @StringRes */ int dialogTitle = ResourceTable.String_cpv_default_title;
        /* @StringRes */ int presetsButtonText = ResourceTable.String_cpv_presets;
        /* @StringRes */ int customButtonText = ResourceTable.String_cpv_custom;
        /* @StringRes */ int selectedButtonText = ResourceTable.String_cpv_select;
        @DialogType
        int dialogType = TYPE_PRESETS;
        int[] presets = MATERIAL_COLORS;
        int color = Color.BLACK.getValue();
        int dialogId = 0;
        boolean showAlphaSlider = false;
        boolean allowPresets = true;
        boolean allowCustom = true;
        boolean showColorShades = true;
        @ColorShape
        int colorShape = ColorShape.CIRCLE;

        ColorPickerDialog dialog;

        /*package*/ Builder() {

        }

        /**
         * Set the dialog title string resource id
         *
         * @param dialogTitle The string resource used for the dialog title
         * @return This builder object for chaining method calls
         */
        public Builder setDialogTitle(/* @StringRes */ int dialogTitle) {
            this.dialogTitle = dialogTitle;
            return this;
        }

        /**
         * Set the selected button text string resource id
         *
         * @param selectedButtonText The string resource used for the selected button text
         * @return This builder object for chaining method calls
         */
        public Builder setSelectedButtonText(/* @StringRes */ int selectedButtonText) {
            this.selectedButtonText = selectedButtonText;
            return this;
        }

        /**
         * Set the presets button text string resource id
         *
         * @param presetsButtonText The string resource used for the presets button text
         * @return This builder object for chaining method calls
         */
        public Builder setPresetsButtonText(/* @StringRes */ int presetsButtonText) {
            this.presetsButtonText = presetsButtonText;
            return this;
        }

        /**
         * Set the custom button text string resource id
         *
         * @param customButtonText The string resource used for the custom button text
         * @return This builder object for chaining method calls
         */
        public Builder setCustomButtonText(/* @StringRes */ int customButtonText) {
            this.customButtonText = customButtonText;
            return this;
        }

        /**
         * Set which dialog view to show.
         *
         * @param dialogType Either {@link ColorPickerDialog#TYPE_CUSTOM} or {@link ColorPickerDialog#TYPE_PRESETS}.
         * @return This builder object for chaining method calls
         */
        public Builder setDialogType(@DialogType int dialogType) {
            this.dialogType = dialogType;
            return this;
        }

        /**
         * Set the colors used for the presets
         *
         * @param presets An array of color ints.
         * @return This builder object for chaining method calls
         */
        public Builder setPresets(/*@NonNull*/ int[] presets) {
            this.presets = presets;
            return this;
        }

        /**
         * Set the original color
         *
         * @param color The default color for the color picker
         * @return This builder object for chaining method calls
         */
        public Builder setColor(int color) {
            this.color = color;
            return this;
        }

        /**
         * Set the dialog id used for callbacks
         *
         * @param dialogId The id that is sent back to the {@link ColorPickerDialogListener}.
         * @return This builder object for chaining method calls
         */
        public Builder setDialogId(int dialogId) {
            this.dialogId = dialogId;
            return this;
        }

        /**
         * Show the alpha slider
         *
         * @param showAlphaSlider {@code true} to show the alpha slider. Currently only supported with the {@link
         *                        ColorPickerView}.
         * @return This builder object for chaining method calls
         */
        public Builder setShowAlphaSlider(boolean showAlphaSlider) {
            this.showAlphaSlider = showAlphaSlider;
            return this;
        }

        /**
         * Show/Hide a neutral button to select preset colors.
         *
         * @param allowPresets {@code false} to disable showing the presets button.
         * @return This builder object for chaining method calls
         */
        public Builder setAllowPresets(boolean allowPresets) {
            this.allowPresets = allowPresets;
            return this;
        }

        /**
         * Show/Hide the neutral button to select a custom color.
         *
         * @param allowCustom {@code false} to disable showing the custom button.
         * @return This builder object for chaining method calls
         */
        public Builder setAllowCustom(boolean allowCustom) {
            this.allowCustom = allowCustom;
            return this;
        }

        /**
         * Show/Hide the color shades in the presets picker
         *
         * @param showColorShades {@code false} to hide the color shades.
         * @return This builder object for chaining method calls
         */
        public Builder setShowColorShades(boolean showColorShades) {
            this.showColorShades = showColorShades;
            return this;
        }

        /**
         * Set the shape of the color panel view.
         *
         * @param colorShape Either {@link ColorShape#CIRCLE} or {@link ColorShape#SQUARE}.
         * @return This builder object for chaining method calls
         */
        public Builder setColorShape(int colorShape) {
            this.colorShape = colorShape;
            return this;
        }

        /**
         * Create the {@link ColorPickerDialog} instance.
         *
         * @return A new {@link ColorPickerDialog}.
         * @see #show(Context)
         */
        public ColorPickerDialog create(Context context) {
            PacMap args = new PacMap();
            args.putIntValue(ARG_ID, dialogId);
            args.putIntValue(ARG_TYPE, dialogType);
            args.putIntValue(ARG_COLOR, color);
            args.putIntValueArray(ARG_PRESETS, presets);
            args.putBooleanValue(ARG_ALPHA, showAlphaSlider);
            args.putBooleanValue(ARG_ALLOW_CUSTOM, allowCustom);
            args.putBooleanValue(ARG_ALLOW_PRESETS, allowPresets);
            args.putIntValue(ARG_DIALOG_TITLE, dialogTitle);
            args.putBooleanValue(ARG_SHOW_COLOR_SHADES, showColorShades);
            args.putIntValue(ARG_COLOR_SHAPE, colorShape);
            args.putIntValue(ARG_PRESETS_BUTTON_TEXT, presetsButtonText);
            args.putIntValue(ARG_CUSTOM_BUTTON_TEXT, customButtonText);
            args.putIntValue(ARG_SELECTED_BUTTON_TEXT, selectedButtonText);
            return create(context, args);
        }

        ColorPickerDialog create(Context context, PacMap args) {
            ColorPickerDialog dialog = new ColorPickerDialog(context, args);
            int width = context.getResourceManager().getDeviceCapability().width;
            dialog.setSize(AttrHelper.vp2px(width, context) - 80, ComponentContainer.LayoutConfig.MATCH_CONTENT);
            return dialog;
        }

        /**
         * Create and show the {@link ColorPickerDialog} created with this builder.
         *
         * @param context The current ability.
         */
        public ColorPickerDialog show(Context context) {
            ColorPickerDialog dialog = create(context);
            dialog.show();
            return dialog;
        }

    }

    // endregion
}
